package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl  extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    EmpMapper empMapper;

    @Autowired
    DeptService deptService;
    @Autowired
    private EmpExprMapper empExprMapper;


    //分页查询
    @Override
    public PageResult<Emp> page(EmpQueryParam param) {
        Integer currentPage = param.getPage();
        Integer pageSize = param.getPageSize();
        String name = param.getName();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
        Integer gender = param.getGender();
        Page<Emp> page =Page.of(currentPage,pageSize);
        //添加降序条件
        page.addOrder(OrderItem.desc("update_time"));
        //查询条件并分页
        this.lambdaQuery().like(!StringUtils.isEmpty(name),Emp::getName,name)
                .between(Objects.nonNull(begin)&&Objects.nonNull(end),Emp::getEntryDate,begin,end)
                .eq(Objects.nonNull(gender),Emp::getGender,gender)
                .page(page);

        //补全部门名称
        page.getRecords().forEach((e)-> {
            Dept dept = deptService.getById(e.getDeptId());
            if (dept!=null){
                e.setDeptName(dept.getName());
            }
        });
        List<Dept> list = deptService.list();
        Map<Long, String> deptMap = list.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        return new PageResult<>(page.getTotal(), page.getRecords());
    }


    //新增员工以及员工工作经历
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveEmpAndExpr(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        log.warn(emp.getId().toString());
        List<EmpExpr> exprList = emp.getExprList().stream().peek(expr->expr.setEmpId(emp.getId())).toList();
        //添加工作经历
        empExprMapper.insert(exprList);
        return Result.success();
    }




    //批量删除
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteEmpAndExpr(List<Integer> ids) {
        try {
            this.removeByIds(ids);
            empExprMapper.delete(new LambdaQueryWrapper<>(EmpExpr.class).in(EmpExpr::getEmpId,ids));
        } catch (Exception e) {
            throw new RuntimeException("defeat");
        }
        return Result.success();
    }

    //根据id修改
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateEmpAndExpr(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empExprMapper.delete(new LambdaQueryWrapper<>(EmpExpr.class).eq(EmpExpr::getEmpId,emp.getId()));
        try {
            this.updateById(emp);
            List<EmpExpr> exprList = emp.getExprList();
            if (CollectionUtil.isNotEmpty(exprList))
            {empExprMapper.insert(exprList.stream().peek(e-> e.setEmpId(emp.getId())).toList());}
        } catch (Exception e) {
            throw new RuntimeException("异常");
        }
        return Result.success();
    }

    //获取员工及员工工作经历
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result getEmpAndExprById(Integer id) {
        Emp emp = this.getById(id);
        emp.setExprList(empExprMapper.selectList(new LambdaQueryWrapper<>(EmpExpr.class).eq(EmpExpr::getEmpId,id)));
        return Result.success(emp);
    }


}
